<?php

//print_r($_POST);
 
// username and password sent from form 

//[user1] => 1 [source] => 11 [inv_id] => 23 [val] => [amount] => 77 [number] => 1 
$user1=$_POST['user1']; 
$source=$_POST['source'];
$code=$_POST['code'];
if(isset($_POST['inv_id'])){
$inv_id=$_POST['inv_id'];
}else{
	if(isset($_POST['scan_code'])){
		
		$inv_id=getInv_id($source,$_POST['scan_code']);
		if(!$inv_id){
			header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=badData");
	        return;
		}
		
	}else{
		header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=missing");
	return;
	}
	
	
}

$val=$_POST['val'];
if(isset($_POST['number'])&&$_POST['number']!=0){
$number=$_POST['number'];
}else{
	header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=missing");
	return;
}
$limit= inventory_limit($inv_id);
echo "limit:".$limit."<br>";
if($limit>=$number){
	$scan_code=inventory_scan_code($inv_id);
	if(isset($_POST['amount'])&&is_numeric($_POST['amount'])){
		$amount=$_POST['amount'];
		
	}else{//get default amount
		$amount=getDefaultPriceByInv_id($inv_id);
		if($amount==0){
			header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=badData");
			
		}
	}
	//echo "limitation passed and scan_code: ".$scan_code."<br>";
	if($val=='unit'){
		
		$amount=$number*$amount;
	}
	//distributeItem($inv_id,$scan_code,$limit,$number,$source,$target,$user1);
	//return;
	
	if(sellItem($inv_id,$scan_code,$limit,$number,$source,$amount,$user1,$code)){
		
		
		//return;
	header("location:../index.php?page=organization_sell&id=".$source."&stat=sold");
	}else{
	header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=badData");
		
	}
	
	
}else{
	header("location:../index.php?page=organization_sell&id=".$source."&stat=error&error=limit");
	
}


?>